package com.eduadmin.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.eduadmin.entity.Category;
import com.eduadmin.service.ICategoryService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class CategoryDataUploadListener extends AnalysisEventListener<Category> {
    private  int count=1;
    //依赖注入
    private final ICategoryService categoryService;
    public CategoryDataUploadListener(ICategoryService categoryService) {
        this.categoryService = categoryService;
    }

    private static final int BATCH_COUNT = 600;
    List<Category> list = new ArrayList<>();

    @Override
    public void invoke(Category data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        count++;
        Category category = categoryService.getCategoryByName(data.getCategoryName());
        if(category==null){
        list.add(data);
        }else {
            log.info("Excel 数据表中第 "+count + " 行 中的类别名称已在数据库中，不能再导入！");
        }
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        if (!CollectionUtils.isEmpty(list)) {
            categoryService.addCategorys(list);
        }
        log.info("存储数据库成功！");
    }


}
